package cn.javazd.demo;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ForTest {

	private static final int COUNT = 2;
	private static List<String> str = new ArrayList<String>();

	// 初始化集合
	public static void init() {
		long start = System.nanoTime();
		for (int i = 0; i < COUNT; i++) {
			str.add("第" + i + "个元素");
		}
		System.out.println("耗时：" + (System.nanoTime() - start) / 1000);
	}

	public static void main(String[] args) {
		init();
		System.out.println("for循环测试结果：" + testFor());
		System.out.println("foreach循环测试结果：" + testForeach());
		System.out.println("iterator循环测试结果：" + testIterator());
		System.out.println("Lambda循环测试结果：" + testLambda());
	}

	public static long testFor() {
		long start = System.nanoTime();
		String s = null;
		for (int i = 0; i < str.size(); i++) {
			s = str.get(i);
		}
		return (System.nanoTime() - start) / 1000;
	}

	public static long testForeach() {
		long start = System.nanoTime();
		String s = null;
		for (String ss : str) {
			s = ss;
		}
		return (System.nanoTime() - start) / 1000;
	}

	public static long testIterator() {
		long start = System.nanoTime();
		String s = null;
		Iterator<String> iterator = str.iterator();
		while (iterator.hasNext()) {
			s = iterator.next();
		}
		return (System.nanoTime() - start) / 1000;
	}

	public static long testLambda() {
		long start = System.nanoTime();
		String s = null;
		str.forEach(System.out::println);
		return (System.nanoTime() - start) / 1000;
	}
}
